<template>
  <div class="chat-container">
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" :class="['message', message.sender]">
        {{ message.text }}
      </div>
    </div>
    <div class="chat-input">
      <input v-model="inputMessage" @keyup.enter="sendMessage" placeholder="Type your message..."/>
      <button @click="sendMessage">Send</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'ChatBot',
  data() {
    return {
      messages: [],
      inputMessage: '',
      apiUrl: 'http://localhost:8000/chat', // 后端API地址
    };
  },
  methods: {
    async sendMessage() {
      if (this.inputMessage.trim() === '') return;

      // 添加用户消息
      this.messages.push({sender: 'human', text: this.inputMessage});
      const userMessage = this.inputMessage;
      this.inputMessage = '';

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });

      try {
        // 发送请求到后端
        const response = await axios.post(this.apiUrl, {message: userMessage});
        const botMessage = response.data.response;

        // 添加机器人消息
        this.messages.push({sender: 'robot', text: botMessage});

        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      } catch (error) {
        console.error('Error sending message:', error);
        this.messages.push({sender: 'robot', text: 'Sorry, there was an error processing your message.'});
      }
    },
    scrollToBottom() {
      const container = this.$refs.messagesContainer;
      container.scrollTop = container.scrollHeight;
    },
  },
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 500px;
  width: 400px;
  border: 1px solid #ccc;
  border-radius: 8px;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.message {
  margin-bottom: 10px;
  padding: 8px;
  border-radius: 4px;
}

.human {
  background-color: #dcf8c6;
  text-align: right;
}

.robot {
  background-color: #fff;
  text-align: left;
}

.chat-input {
  display: flex;
  border-top: 1px solid #ccc;
}

.chat-input input {
  flex: 1;
  padding: 10px;
  border: none;
  outline: none;
}

.chat-input button {
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  cursor: pointer;
}

.chat-input button:hover {
  background-color: #0056b3;
}
</style>